import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: () => import('@/Layout/Layout.vue'),
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import('@/views/Home/Home.vue'),
          redirect: { name: 'chat' },
          children:[
            {
              path: 'chat',
              name: 'chat',
              components: {
                aside: () => import('@/views/Chat/ChatAside.vue'),
                default: () => import('@/views/Chat/ChatCover.vue')
              }
            },
            {
              path: 'chat/:id',
              name: 'chat-id',
              components: {
                aside: () => import('@/views/Chat/ChatAside.vue'),
                default: () => import('@/views/Chat/ChatContent/ChatConetnt.vue')
              }
            },
            {
              path:'contact',
              name:'contact',
              components: {
                aside: () => import('@/views/Contact/ContactAside.vue'),
                default: () => import('@/views/Contact/ContactCover.vue')
              }
            },
            {
              path:'contact/:id',
              name:'contact-id',
              components: {
                aside: () => import('@/views/Contact/ContactAside.vue'),
                default: () => import('@/views/Contact/ContactDetail.vue')
              }
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register/Register.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notfound',
      component: () => import('@/views/NotFound/NotFound.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (to.name !== 'login' && to.name !== 'register' && !userStore.token) {
    ElMessage.warning('请先登录')
    next({ name: 'login' })
  }
  next()
})

export default router
